package cn.tedu.jdbc;

import cn.tedu.Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 使用预编译SQL实现注册功能
 * 1，用户输入：用户名，密码，昵称，年龄；
 * 2，返回结果：
 * 2.1用户名被占用[select....from userinfo where username =?]
 * 2.2注册成功[insert into userinfo (username,password,nickname,age)values(?,?,?,?)]
 */
public class JDBCRcg {
    public static void main(String[] args) {
        try(Connection connection = DBUtil.getConnection()){
            //接受用户名和密码
            Scanner scanner = new Scanner(System.in);
            System.out.println("用户名：");
            String username = scanner.nextLine();
            System.out.println("密码：");
            String password = scanner.nextLine();
            System.out.println("昵称：");
            String nickname = scanner.nextLine();
            System.out.println( "年龄：");
            Integer age = scanner.nextInt();
            //用户名被占用
            String sql = "select username from userinfo where username =?";
            PreparedStatement ps = connection.prepareStatement(sql);
            //设置？的值
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            //注册成功
            if(rs.next()){
                System.out.println("该用户名被占用");
            }else{//用户名被占用
                String sql1 = "insert into userinfo (username,password,nickname,age)values(?,?,?,?)";
                PreparedStatement ps1 = connection.prepareStatement(sql1);
                ps1.setString(1, username);
                ps1.setString(2, password);
                ps1.setString(3, nickname);
                ps1.setInt(4, age);
                int i = ps1.executeUpdate();
                if(i>0){
                    System.out.println("恭喜您，注册成功");
                }else{
                    System.out.println("系统繁忙，请稍后再试");
                }
            }
    }catch (SQLException e){
        throw new RuntimeException(e);
        }
    }
}
